// 页面路径：store/index.js 
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);//vue的插件机制

//Vuex.Store 构造器选项
const store = new Vuex.Store({
  state: {//存放状态
    cartList: uni.getStorageSync("cartList") || [],
    storageAddress: uni.getStorageSync("storageAddress"),
    token:''
  },
  getters: {
    // 
    address(state) {
      if (Date.now() - state.storageAddress.time <= 1000 * 60 * 5) {
        return state.storageAddress.data
      }
    },

    // 选中的商品
    goodsCheckList(state) {
      return state.cartList.filter(item => item.checked)
    },
    // 选中的商品总价
    totalPrice(state, getters) {
      return getters.goodsCheckList.reduce((total, goods) => total += goods.goods_price * goods.num, 0);
    },
    // 选中的商品总数
    totalNum(state, getters) {
      return getters.goodsCheckList.reduce((total, goods) => total += goods.num, 0);
    },

    // 是否全选
    isAllCheck(state) {
      return (
        state.cartList.length && state.cartList.every((item) => item.checked)
      );
    },
  },
  mutations: {
    //缓存地址
    setAddress(state, data) {
      state.storageAddress = { time: Date.now(), data }
      uni.setStorageSync("storageAddress", state.storageAddress)
    },

    //设置cartList
    setCartList(state, cartList) {
      state.cartList = cartList

      //缓存
      uni.setStorageSync("cartList", cartList)
    },

    //设置token
    setToken(state, data) {
      state.token=data
     }
  },
  actions: {
    async handleToken(store) {

      //获取用户信息
      const [err1, { encryptedData, rawData, iv, signature }] =
        await uni.getUserProfile({
          desc: "为了干坏事",
        });

      //获取登录凭证code
      const [err2, { code }] = await uni.login();
      // console.log(code);

      const tokenParams = {
        encryptedData,
        rawData,
        iv,
        signature,
        code,
      };

      //获取用户token
      const res1 = await uni.$u.post("/users/wxlogin", tokenParams);
      const { token } = res1.message;
      // console.log(token)
      store.commit("setToken",token)

    }
  }
})
export default store